<?php
/**
 * 返回成功json
 * @param mixed $data 返回的数据
 * @param integer $code 状态码
 * @param array $header 头部
 * @param array $options 参数
 * @return \think\response\Json
 */
function success($data = [], $code = 200, $msg = "操作成功", $header = [])
{
    
    $result = [
        'code' => $code,
        'msg' => $msg,
        'time' => request()->time(),
        'data' => $data,
    ];
    return json($result, 200, $header);
}

 /**
 * 获取\think\response\Json对象实例
 * @param mixed $data 返回的数据
 * @param integer $code 状态码
 * @param array $header 头部
 * @param array $options 参数
 * @return \think\response\Json
 */
function error($msg = "网络异常，请重试", $code = 400, $data = [], $header = [])
{
    $result = [
        'code' => $code,
        'msg' => $msg,
        'time' => request()->time(),
        'data' => $data,
    ];
    return json($result, 200, $header);
}

/**
 * POST请求
 * @param  [type] $url     [description]
 * @param  array  $data    [description]
 * @param  array  $headers [description]
 * @return [type]          [description]
 */
if (!function_exists('http_post')) {
    function http_post($url,$data = array(),$headers=array())
    {
        $curl = curl_init();
        if( count($headers) >= 1 ){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        return $output;
    }
}

/**
 * 隐藏手机号中间四位
 * @param $str
 * @return string|string[]
 */
function hide_phone($str){
    if(is_mobile($str)){
        $str=substr_replace($str,'****',3,4);
    }
    return $str;
}

/**
 * 判断输入的字符串是否是一个合法的电话号码（仅限中国大陆）
 * @param string $string
 * @return boolean
 */
function is_phone($string)
{
  
    return preg_match('/^[0,4,8]\d{2,3}-\d{7,8}$/', $string);
}

/**
 * 写入日志
 */
function write_log($values, $dir)
{
    if (is_array($values))
        $values = print_r($values, true);
    // 日志内容
    $content = '[' . date('Y-m-d H:i:s') . ']' . PHP_EOL . $values . PHP_EOL . PHP_EOL;
    try {
        // 文件路径
        $filePath = $dir . '/logs/';
        // 路径不存在则创建
        !is_dir($filePath) && mkdir($filePath, 0755, true);
        // 写入文件
        return file_put_contents($filePath . date('Ymd') . '.log', $content, FILE_APPEND);
    } catch (\Exception $e) {
        return false;
    }
}

//获取安全的JSON 或数组
function security_json_or_array($str)
{
    if (is_array($str)) {
        $datas = $str;
    } else {
        $datas = json_decode($str, true);
        if (json_last_error() != JSON_ERROR_NONE) {
            return [];
        }
    }
    if (empty($datas)) return [];
    $return = [];
    foreach ($datas as $key => $val) {
        if (is_array($val)) {
            $return[$key] = security_json_or_array($val);
        } else {
            $return[$key] = security_editor_textarea($val);
        }
    }
    return $return;
}
//获取安全的textarea
function security_editor_textarea($str)
{
    $farr = [
//        "/\s+/", //过滤多余的空白
        "/<(\/?)(script|i?frame|style|html|body|title|link|meta|\?|\%)([^>]*?)>/isU",
        "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU"
    ];
    $tarr = [
//        " ",
        "＜\\1\\2\\3＞",
        "\\1\\2",
    ];
    $str = preg_replace($farr, $tarr, $str);

    return $str;
}

function randCode($num=6){
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $password = '';
    for ($i = 0; $i < $num; $i++) {
        $index = mt_rand(0, strlen($characters) - 1);
        $password .= $characters[$index];
    }
    return $password;
}